package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.elite.groovy.util.Util;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import com.elite.groovy.kh.DHAESUtil;

/**
 * 
 * 使用说明： 官微调用接口，建议反馈工单同步到客服系统
 *
 */


 public  class GwfkOrder implements ServiceBackInvoke{
  public static final Log log = LogFactory.getLog(GwfkOrder.class);
  public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response){
		log.debug("-----Begin 官微建议反馈工单----------");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		String aesReq =Util.getRequestBody(request, "UTF-8");
		log.debug("aesReq:" + aesReq);

		request.getParameter("interfacetype")
		//获取接口请求类型：create 官微建议新建/search 官微建议查询
		String v_interfacetype=request.getParameter("interfacetype");
		log.debug("v_interfacetype:"+v_interfacetype);
		try{

			//官微建议新建
			if(v_interfacetype=='create'){


				JSONObject aesJson  = new JSONObject().fromObject(aesReq);
				String aesData=aesJson.getString("data");

				//aes密钥
				String assertKey = "+ZAb13}Pi0xQ!lVu";
				//aes解密
				log.debug("解密前数据官微建议是："+aesData);
				String requestJSONStr=DHAESUtil.decrypt(aesData,assertKey);
				log.debug("解密后数据官微建议是："+requestJSONStr);
			
			
				JSONObject json  = new JSONObject().fromObject(requestJSONStr);

				
				String v_channelsource = "";
				if(json.has("channelsource")&&json.getString("channelsource").length()>0){//数据来源
					v_channelsource = json.getString("channelsource");               
				}else{
					//返回失败结果
					JSONObject  jsonALL3 = new JSONObject();
					jsonALL3.put("retCode", "-1");
					jsonALL3.put("retMessage", "数据来源不能为空");
					jsonALL3.put("data", "");
					return jsonALL3;
				}
				String v_customername = "";
				if(json.has("customername")&&json.getString("customername").length()>0){ //客户姓名
					v_customername = json.getString("customername");
				}else{
					//返回失败结果
					JSONObject  jsonALL3 = new JSONObject();
					jsonALL3.put("retCode", "-1");
					jsonALL3.put("retMessage", "客户姓名不能为空");
					jsonALL3.put("data", "");
					return jsonALL3;
				}
				String v_mobile = "";
				if(json.has("mobile")&&json.getString("mobile").length()>0){//联系方式
					v_mobile = json.getString("mobile");       	  		
				}else{
					//返回失败结果
					JSONObject  jsonALL3 = new JSONObject();
					jsonALL3.put("retCode", "-1");
					jsonALL3.put("retMessage", "联系方式不能为空");
					jsonALL3.put("data", "");
					return jsonALL3;
				}
				
				String v_content = "";
				if(json.has("content")){//内容描述
					 v_content = json.getString("content");        		
				}
				String v_title ="";
				if(json.has("title")){//标题
					 v_title = json.getString("title");					
				}
				String v_userid ="";
				if(json.has("userID")){//官微传递userID
					v_userid = json.getString("userID");					
				}
				String v_isnwemployee ="";
				if(json.has("isnwemployee")){//官微传递userID
					v_isnwemployee = json.getString("isnwemployee");					
				}
				

				//生成objective_guid  工单号
				def querysql11="select sysguid objective_guid,'GWFK'||to_char(sysdate,'YYYYMMDDhh24mi')||(case when SEQ_GWZTSORDER.nextval>=1 and SEQ_GWZTSORDER.nextval<10 then '000'||SEQ_GWZTSORDER.nextval  when SEQ_GWZTSORDER.nextval>=10 and SEQ_GWZTSORDER.nextval<100  then '00'||SEQ_GWZTSORDER.nextval  when SEQ_GWZTSORDER.nextval>=100 and SEQ_GWZTSORDER.nextval<1000  then '0'||SEQ_GWZTSORDER.nextval else to_char(SEQ_GWZTSORDER.nextval)end) workorderid from dual";
				def list11=eliteBean.chaxun_sql(querysql11,"dataSource");
				def map11=list11[0];
				def v_objective_guid=map11.get("objective_guid");
				def v_workorderid=map11.get("workorderid");
			 
				//生成 tabc 
				def updatesql6="insert into tabcorder_gwfk(ORDER_ID,ORDER_NO,ORDER_SOURCE,CUSTOMER_NAME,MOBILE, CREATE_TIME, TITLE,COMMENTS,user_id,isnwemployee,deal_status)values('"+v_objective_guid+"','"+v_workorderid+"','"+v_channelsource+"','"+v_customername+"','"+v_mobile+"',to_char(sysdate,'yyyy-mm-dd hh24:mi:ss'),'"+v_title+"','"+v_content+"','"+v_userid+"','"+v_isnwemployee+"','0')";
				def updatesqlresult6=eliteBean.update(updatesql6,"dataSource");
				
				//保存照片
				if(json.has("photos")){//官微传递图片集
					JSONArray  v_photos = json.getJSONArray("photos");	
					for(int i=0;i<v_photos.size();i++){
						String v_url = v_photos.get(i);
						def updatephoto="insert into uploadlist (UPLOADGUID, CREATEDATE, PATH ,FILENAME ,STAFF_ID, GUID,CONFIDENTIAL_TYPE ,UPLOAD_STATUS) values(sysguid,sysdate,'"+v_url+"','','000146','"+v_objective_guid+"','1','0')";
						def updatephotoresult=eliteBean.update(updatephoto,"dataSource");
					}
				}
				
				
				String aesResData=DHAESUtil.encrypt("{\"workorderid\":\""+v_workorderid+"\"}",assertKey);
				
				//返回成功结果
				JSONObject  jsonALL3 = new JSONObject();
				jsonALL3.put("retCode", "1");
				jsonALL3.put("retMessage", "success");
				jsonALL3.put("data", aesResData);
				return jsonALL3;
				
			}
		}catch(Exception e){
			log.debug("新建官微建议反馈工单错误："+e);
			
			//返回失败结果
			JSONObject  jsonALL3 = new JSONObject();
			jsonALL3.put("retCode", "-1");
			jsonALL3.put("retMessage", e.getMessage());
			jsonALL3.put("data", "");
			return jsonALL3;
		}
		try{
			if(v_interfacetype=='search'){
				
				
				JSONObject aesJson  = new JSONObject().fromObject(aesReq);
				String aesData=aesJson.getString("data");

				//aes密钥
				String assertKey = "+ZAb13}Pi0xQ!lVu";
				//aes解密

				log.debug("解密前数据data是："+aesData);
				String requestJSONStr=DHAESUtil.decrypt(aesData,assertKey);
				log.debug("解密后数据32212是："+requestJSONStr);
				
				def SQL4="";
				
				JSONObject json  = new JSONObject().fromObject(requestJSONStr);
				
				String v_userID ="";
				if(json.has("userID")){//官微userID
					v_userID = json.getString("userID");        				
				}

				log.debug("v_userID:"+v_userID);
				
				boolean flag = false;
				
				if(v_userID !="" && v_userID != null && !"null".equals(v_userID)){
					 SQL4 ="and  user_id='"+v_userID+"'";
					 flag= true;
				}
				log.debug("SQL4:"+SQL4);
				if(!flag){
					JSONObject  jsonALL1 = new JSONObject();
					jsonALL1.put("retCode", "-1");
					jsonALL1.put("retMessage","查询失败，请输入查询条件");
					jsonALL1.put("data", "");
					log.debug("jsonALL1:"+jsonALL1);
					return jsonALL1; 
				}
				
				//官网受理单查询
				def querysql20="select count(*) count2 from tabcorder_gwfk where 1=1 "+SQL4+" ";
				def list20=eliteBean.chaxun_sql(querysql20,"dataSource");
				def map20=list20[0];
				def v_count2=map20.get("count2");
				
				if(v_count2>0){
					def querysq2l="SELECT order_id v_guid,title v_title,comments v_content,user_id v_userID,create_time v_createddate,customer_name v_customername,mobile v_mobile,case when deal_status='2' then '已完成' else '处理中' end v_statudesc,'鼎和回复：'||remark v_reply, deal_time v_replydate FROM tabcorder_gwfk  where 1=1 "+SQL4+" order by create_time desc";			
					List<?> l =eliteBean.chaxun_sql(querysq2l,"dataSource");
					int count=l.size();
					if(count>=1) {
						JSONObject ja = new JSONObject();
						JSONObject jb = new JSONObject();
						JSONArray jc = new JSONArray();
						ja.put("retCode", "1");
						ja.put("retMessage", "success");
						for(int i = 0;i<l.size();i++){
							jb.clear();
							Map<?, ?> m = (Map<?, ?>) l.get(i);
							log.debug("Query:"+m.toString());
							jb.put("title", m.get("v_title")  ==null?"":(String)m.get("v_title"));
							jb.put("content", m.get("v_content")  ==null?"":(String)m.get("v_content"));
							jb.put("reply", m.get("v_reply")  ==null?"":(String)m.get("v_reply"));
							
							def queryPhotos = "select path from uploadlist where guid = '"+m.get("v_guid")+"' ";
							List<?> photos =eliteBean.chaxun_sql(queryPhotos,"dataSource");
							def photostr = "";
							if(photos.size()>=1){
								JSONArray JSONarrPhotos = new JSONArray();
								for(int j=0;j<photos.size();j++){
									Map<?, ?> p = (Map<?, ?>)photos.get(j);
									JSONarrPhotos.add((String)p.get("PATH"))
								}
								photostr = JSONarrPhotos.toString();
							}
							jb.put("photos",photostr);
							jb.put("customername", m.get("v_customername")  ==null?"":(String)m.get("v_customername"));
							jb.put("mobile", m.get("v_mobile")  ==null?"":(String)m.get("v_mobile"));
							jb.put("createddate", m.get("v_createddate")  ==null?"":(String)m.get("v_createddate")); 
							jb.put("replydate", m.get("v_replydate")  ==null?"":(String)m.get("v_replydate"));
							jb.put("statudesc", m.get("v_statudesc")  ==null?"":(String)m.get("v_statudesc"));
							jc.add(jb);
						}
						
						String jcStr = jc.toString();
						log.debug("加密前:"+jcStr);
						String aesResData=DHAESUtil.encrypt(jcStr,assertKey);
						log.debug("加密后:"+aesResData);
						ja.put("data", aesResData);
						return ja;
					}
				}else{
					JSONObject  jsonALL1 = new JSONObject();
					jsonALL1.put("retCode", "1");
					jsonALL1.put("retMessage","查询成功，未查询相关内容");
					jsonALL1.put("data", "");
					log.debug("jsonALL1:"+jsonALL1);
					return jsonALL1; 
				
				}
			}
		}catch(Exception e){
			log.debug("查询官网投诉与建议工单错误："+e);
			
			//返回失败结果
			JSONObject  jsonALL3 = new JSONObject();
			jsonALL3.put("retCode", "-1");
			jsonALL3.put("retMessage", e.getMessage());
			jsonALL3.put("data", "");
			return jsonALL3;
		}
		log.debug("-----End 官微建议反馈工单----------");
      }  
        
 }
